package com.example.wancaibooking.service;

import android.content.Context;
import android.os.Environment;

import com.example.wancaibooking.R;
import com.example.wancaibooking.entitys.Payout;
import com.example.wancaibooking.entitys.Statistics;
import com.example.wancaibooking.service.base.BaseService;
import com.example.wancaibooking.utils.DateUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import jxl.Workbook;
import jxl.write.*;
import jxl.write.Number;

public class StatisticsService extends BaseService {
    public static final String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath() + "/Accounting/Export/";
    private PayoutService payoutService;
    private UserService userService;
    private AccountBookService accountBookService;
    private List<String> keyList;

    public StatisticsService(Context context) {
        super(context);
        payoutService = new PayoutService(context);
        userService = new UserService(context);
        accountBookService = new AccountBookService(context);
    }

    public List<Statistics> getStatisticses(int accountBookId) {
        List<Payout> payouts = payoutService.getPayoutListByAccountBookId(accountBookId);
        HashMap<String, String> hashUsers = userService.getUserToHashMap();
        String[] payoutType = context.getResources().getStringArray(R.array.PayoutType);
        List<Statistics> statisticses = new ArrayList<>();
        Payout payout;
        for (int i = 0; i < payouts.size(); i++) {
            payout = payouts.get(i);
            if (payout.getPayoutType().equals(payoutType[0])) {
                String[] avgUsers = payout.getPayoutUserId().split(",");
                for (int a = 0; a < avgUsers.length; a++) {
                    Statistics statistics = new Statistics();
                    statistics.payerUserId = hashUsers.get(avgUsers[0]);
                    statistics.consumerUserId = hashUsers.get(avgUsers[a]);
                    statistics.cost = payout.getAmount().divide(
                            new BigDecimal(avgUsers.length),
                            2,
                            BigDecimal.ROUND_HALF_EVEN);
                    statisticses.add(statistics);
                }
            } else if (payout.getPayoutType().equals(payoutType[1])) {
                String[] loadUsers = payout.getPayoutUserId().split(",");
                for (int a = 1; a < loadUsers.length; a++) {
                    Statistics statistics = new Statistics();
                    statistics.payerUserId = hashUsers.get(loadUsers[0]);
                    statistics.consumerUserId = hashUsers.get(loadUsers[a]);
                    statistics.cost = payout.getAmount().divide(
                            new BigDecimal(loadUsers.length - 1),
                            2,
                            BigDecimal.ROUND_HALF_EVEN);
                    statisticses.add(statistics);
                }
            } else {
                String[] paersonalUser = payout.getPayoutUserId().split(",");
                Statistics statistics = new Statistics();
                statistics.payerUserId = hashUsers.get(paersonalUser[0]);
                statistics.consumerUserId = hashUsers.get(paersonalUser[0]);
                statistics.cost = payout.getAmount();
                statisticses.add(statistics);
            }
        }
        return statisticses;
    }

    public HashMap<String, BigDecimal> parseStatistics(List<Statistics> statisticses) {
        HashMap<String, BigDecimal> parsedStatisticses = new HashMap<>();
        keyList = new ArrayList<>();
        String key = "";
        for (int i = 0; i < statisticses.size(); i++) {
            Statistics statistics = statisticses.get(i);
            if (statistics.payerUserId.equals(statistics.consumerUserId)) {
                key = statistics.payerUserId + "2";
            } else {
                key = statistics.consumerUserId + "2" + statistics.payerUserId;
            }
            if (parsedStatisticses.containsKey(key)) {
                parsedStatisticses.put(key, parsedStatisticses.get(key).add(statistics.cost));
            } else {
                parsedStatisticses.put(key, statistics.cost);
                keyList.add(key);
            }
        }
        return parsedStatisticses;
    }

    public String getPayoutUserIdByAccountBookId(int accountBookId) {
        HashMap<String, BigDecimal> parsedStatisticses = parseStatistics(getStatisticses(accountBookId));

        String result = "";
        String key = "";
        for (int i = 0; i < keyList.size(); i++) {
            key = keyList.get(i);
            String[] keyInfo = key.split("2");
            if (keyInfo.length == 1) {
                result += keyInfo[0] + "个人消费" + parsedStatisticses.get(key).toString() + "元\r\n";
            } else if (keyInfo.length > 1) {
                result += keyInfo[0] + "应付给" + keyInfo[1] + parsedStatisticses.get(key).toString() + "元\r\n";
            }
        }
        return result;
    }

    public String exportStatistics(int accountBookId) throws Exception {
        String result = "";
        //判断是否有外存储设备
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String accountBookName = accountBookService.getAccountBookNameById(accountBookId);
            String fileName = accountBookName + DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD) + ".xls";
            System.out.println(SDCARD_PATH + fileName);
            File fileDir = new File(SDCARD_PATH);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(SDCARD_PATH + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            //声明一个可写的表对象
            WritableWorkbook workBookData;
            //创建工作薄,需要告诉它往哪个文件里边创建
            workBookData = Workbook.createWorkbook(file);
            //创建工作表,相当于Excel的Sheet1、Sheet2，注意索引从0开始
            WritableSheet wsAccountBook = workBookData.createSheet(accountBookName, 0);

            String[] titles = {"编号", "姓名", "消费信息", "金额"};
            //声明一个标签
            Label label;
            //添加标题行
            for (int i = 0; i < titles.length; i++) {
                //参数1列，2行，3内容
                label = new Label(i, 0, titles[i]);
                //将标签填入一个单元格
                wsAccountBook.addCell(label);
            }
            //添加行
            HashMap<String, BigDecimal> totaList = parseStatistics(getStatisticses(accountBookId));
            for (int i = 0; i < keyList.size(); i++) {
                //添加编号列，参数：1列，2行，3内容
                Number idCell = new Number(0, i + 1, i + 1);
                wsAccountBook.addCell(idCell);
                String[] names = keyList.get(i).split("2");
                Label nameLabel = new Label(1, i + 1, names[0]);
                wsAccountBook.addCell(nameLabel);
                Label infoLabel = null;
                if (names.length == 1) {
                    infoLabel = new Label(2, i + 1, "个人消费");
                } else if (names.length > 1) {
                    infoLabel = new Label(2, i + 1, "付给" + names[1]);
                }
                wsAccountBook.addCell(infoLabel);

                // 格式化金额类型显示，#。##表示格式化为小数点后两位
                NumberFormat moneyFormat = new NumberFormat("#,##");
                WritableCellFormat wcf = new WritableCellFormat(moneyFormat);

                Number moneyLabel = new Number(3, i + 1, totaList.get(keyList.get(i)).doubleValue(), wcf);
                wsAccountBook.addCell(moneyLabel);

            }
            //写入SD卡
            workBookData.write();
            workBookData.close();
            result = "数据已经导出！文件位置：" + SDCARD_PATH + fileName;
        } else {
            result = "未检测到SD卡，数据导出失败";
        }
        return result;
    }
}
